home *** CD-ROM | disk | FTP | other *** search
- /* os_mac.c
- * 12Sep92 e adapted from the file of the same name in the Gambit Project
- * Macintosh specific stuff (for THINK C 7 or CodeWarrior 4 compiler).
- * portions Copyright © 1992-1994 Marc Feeley and Douglas H. Currie, Jr.
- */
-
- #ifdef THINK_C
- #include <MacHeaders>
- #else
- #ifdef __MWERKS__
- #else
- "Unknown compiler!"
- #endif
- #endif
-
- #include "os_mac.h"
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <errno.h>
- #include <signal.h>
- #ifdef THINK_C
- #include <ansi_e.h>
- #else
- Boolean XlateRETURN = 0;
- #endif
-
- /*---------------------------------------------------------------------------*/
-
- #include <Files.h>
- #include <Gestalt.h>
- #include <AppleEvents.h>
- #include <AERegistry.h>
-
- static void init_ae();
-
- #if ( CREATOR == 'Moml' )
- char *image_name = 0; // May97 e
- FSSpec appFSS;
- #endif
- static Boolean been_there_done_that = false;
- char gReceivedAE = 0;
- Boolean gMadeAppFSS = false;
- Boolean gDoQuit = false;
- Boolean gHasAppleEvents = false;
- Boolean gPrintPage = false;
- Boolean gHasStdFile = false;
- Boolean gCursRgnOK = false;
- Boolean gInBackground = false;
- Boolean gLowMemory = false;
- Boolean gSpareBool;
-
- // Boolean gHasWNE = true;
- // Boolean gHasHWPriv = true;
-
- static Handle rainy_day_fund;
- #define kRamReserve 65536
- #define kRamSlop 16384
-
- Ptr empty_buffer;
-
- #include "os_mac_eventchk.h"
- long next_eventchk_ticks;
-
- /*---------------------------------------------------------------------------*/
-
- TextStyle prefStylNormal =
- { monaco, 0, 0, FontSize, { 65536, 65536, 65536 } /* RGBColor Black */ };
- TextStyle prefStylHilite =
- { monaco, 0, 0, FontSize, { 65536, 65536, 65536 } /* RGBColor Black */ };
-
- short prefTabs = dfltTabs;
- short prefWrap = dfltWrap;
- short prefAutoInd = dfltAutoInd;
-
- short current_menus;
-
- MenuHandle menus[7];
-
- Cursor watch_cursor;
- Cursor gc_cursor;
- Cursor ibeam_cursor;
- Cursor *current_cursor;
-
- unsigned char *find_string, *replace_string;
-
- Boolean find_ci = FALSE;
- Boolean find_wrap = FALSE;
-
- static Boolean smKeyBdP;
- static Boolean showPosnP;
-
- short interaction_id = 0;
- short interrupted = 0;
-
- static struct {
- WindowPtr wptr;
- ControlHandle vscroll;
- ControlHandle hscroll;
- TeHANDLE hTE;
- short bold_input;
- short height;
- short dirty;
- short out_len;
- long pos, len;
- char *buf;
- Handle out_buf;
- long needs_inval_ticks;
- char in_use;
- char is_file; // 0: console, 1: new, 2: fss good
- FSSpec fss;
- } wind_table[MAX_NB_WINDOWS];
-
- #define WINDOW_OWNS_FILE_P( id, fss ) \
- (wind_table[id].in_use != 0 && \
- wind_table[id].is_file == 2 && \
- wind_table[id].fss.vRefNum == fss->vRefNum && \
- wind_table[id].fss.parID == fss->parID && \
- (compare_p_to_p( wind_table[id].fss.name, fss->name ) == 0))
-
- RgnHandle gCursorRgn;
-
- long gWaitTicksBG = 20; /* in ticks, should be 6..60 */
- long gWaitTicksFG = 1; /* in ticks, should be 1..15 */
-
- /* */
-
- static void setup_cursors()
- { CursHandle hCurs;
- hCurs = GetCursor(watchCursor);
- watch_cursor = **hCurs;
- /* 28Jan93 e
- hCurs = GetCursor(gc_cursorID);
- gc_cursor = **hCurs;
- */
- hCurs = GetCursor(iBeamCursor);
- ibeam_cursor = **hCurs;
-
- current_cursor = &watch_cursor;
- }
-
- static void ParamText1( Str255 text )
- {
- ParamText( text, "\p", "\p", "\p" );
- }
-
- /* *** preferences saved to disk *** */
-
- static OSErr findPrefFolder( short *foundVRefNum, long *foundDirID )
- {
- *foundVRefNum = 0;
- *foundDirID = 0;
- /* MacTraps2 has FindFolder() glue */
- return FindFolder( kOnSystemDisk, kPreferencesFolderType, kCreateFolder,
- foundVRefNum, foundDirID );
- }
-
- struct prefs
- { short version;
- short tabs;
- short wrap;
- Boolean find_ci;
- Boolean find_wrap;
- Boolean spare0; /* smKeyBdP in Gambit */
- Boolean showPosnP;
- short spare2;
- short spare3;
- short autoInd;
- TextStyle stylNormal;
- TextStyle stylHilite;
- unsigned char fontnmNormal[64];
- unsigned char fontnmHilite[64];
- };
-
- void savePrefs( ConstStr255Param fn )
- {
- short rRef;
- OSErr err;
- struct prefs **hRes;
- struct prefs *pRes;
- short foundVRefNum;
- long foundDirID;
- Str255 fontnmNormal, fontnmHilite;
-
- err = findPrefFolder( &foundVRefNum, &foundDirID );
- if( err != noErr ) return;
-
- if( ( rRef = HOpenResFile( foundVRefNum, foundDirID, fn, fsRdWrPerm ) ) < 0)
- { HCreateResFile( foundVRefNum, foundDirID, fn );
- { HFileInfo pb;
- pb.ioCompletion = (void *)0;
- pb.ioNamePtr = (StringPtr )fn;
- pb.ioVRefNum = foundVRefNum;
- pb.ioFDirIndex = 0;
- pb.ioDirID = foundDirID;
- err = PBHGetFInfoSync( (HParmBlkPtr )&pb );
- pb.ioCompletion = (void *)0;
- pb.ioNamePtr = (StringPtr )fn;
- pb.ioVRefNum = foundVRefNum;
- pb.ioFDirIndex = 0;
- pb.ioDirID = foundDirID;
- pb.ioFlFndrInfo.fdCreator = CREATOR;
- pb.ioFlFndrInfo.fdType = 'gamP';
- if( err == noErr )
- PBHSetFInfoSync( (HParmBlkPtr )&pb );
- }
- rRef = HOpenResFile( foundVRefNum, foundDirID, fn, fsRdWrPerm );
- }
- if( rRef < 0 )
- return;
- hRes = (struct prefs **)GetResource('ePrf', 357);
- if( hRes == 0 || rRef != HomeResFile( (Handle )hRes ) )
- { hRes = (struct prefs **)NewHandle( sizeof( struct prefs ) );
- if( hRes == 0 )
- { CloseResFile( rRef );
- return;
- }
- AddResource( (Handle )hRes, (ResType )'ePrf', 357, (ConstStr255Param)"\p" );
- if( LMGetResErr() != noErr )
- { DisposeHandle( (Handle )hRes );
- CloseResFile( rRef );
- return;
- }
- }
- pRes = *hRes;
- (*pRes).version = 1;
- (*pRes).tabs = prefTabs;
- (*pRes).wrap = prefWrap;
- (*pRes).find_ci = find_ci;
- (*pRes).find_wrap = find_wrap;
- (*pRes).spare0 = 0;
- (*pRes).showPosnP = showPosnP;
- (*pRes).spare2 = 0;
- (*pRes).spare3 = 0;
- (*pRes).autoInd = prefAutoInd;
- (*pRes).stylNormal = prefStylNormal;
- (*pRes).stylHilite = prefStylHilite;
- GetFontName( prefStylNormal.tsFont, fontnmNormal );
- if( fontnmNormal[0] > 63 ) fontnmNormal[0] = 63;
- p_to_p( fontnmNormal, (**hRes).fontnmNormal );
- GetFontName( prefStylHilite.tsFont, fontnmHilite );
- if( fontnmHilite[0] > 63 ) fontnmHilite[0] = 63;
- p_to_p( fontnmHilite, (**hRes).fontnmHilite );
-
- ChangedResource( (Handle )hRes );
- CloseResFile( rRef );
- }
-
- static void readPrefs( ConstStr255Param fn )
- {
- short rRef;
- OSErr err;
- struct prefs **hRes;
- struct prefs *pRes;
- short foundVRefNum;
- long foundDirID;
-
- err = findPrefFolder( &foundVRefNum, &foundDirID );
- if( err != noErr ) return;
-
- rRef = HOpenResFile( foundVRefNum, foundDirID, fn, fsRdWrPerm );
- /* don't test rRef here since resource may come from elsewhere, e.g., from appl. */
- hRes = (struct prefs **)GetResource('ePrf', 357);
- if( hRes != 0 )
- { pRes = *hRes;
- if( (*pRes).version == 1 )
- { prefTabs = (*pRes).tabs;
- prefWrap = (*pRes).wrap;
- find_ci = (*pRes).find_ci;
- find_wrap = (*pRes).find_wrap;
- prefAutoInd = (*pRes).autoInd;
- showPosnP = (*pRes).showPosnP;
- prefStylNormal = (*pRes).stylNormal;
- prefStylHilite = (*pRes).stylHilite;
- GetFNum( (**hRes).fontnmNormal, &prefStylNormal.tsFont );
- if( prefStylNormal.tsFont < 0 ) prefStylNormal.tsFont = 0;
- GetFNum( (**hRes).fontnmHilite, &prefStylHilite.tsFont );
- if( prefStylHilite.tsFont < 0 ) prefStylHilite.tsFont = 0;
- }
- }
- if( rRef >= 0 ) CloseResFile( rRef );
- }
-
- /* *** */
-
- #define fustItem 3
- static short itemtowindid[MAX_NB_WINDOWS];
- static short windidtodigit[MAX_NB_WINDOWS];
- static short qWindItems = 0;
-
- #if GENERATINGPOWERPC
- #pragma options align=mac68k
- #endif
-
- typedef struct { short nbmenus6, right, dummy; struct { MenuHandle mh; short left; } menu[100]; } menu_list;
-
- #if GENERATINGPOWERPC
- #pragma options align=reset
- #endif
-
- static short cmd_key_exists( char c )
- {
- menu_list **ml = (menu_list **)LMGetMenuList();
- short n = (*ml)->nbmenus6/6;
- short i, j, m, cmd;
- for (i=0; i<n; i++)
- { MenuHandle mh = (*ml)->menu[i].mh;
- m = CountMItems( mh );
- for (j=1; j <= m; j++)
- {
- GetItemCmd( mh, j, &cmd );
- if (cmd == c) return 1;
- }
- }
- return 0;
- }
-
- static void addWindMenuItem( short id )
- { short d, i, j;
- Str255 title, key = "\p / ";
- WindowPtr wind = wind_table[id].wptr;
- if (qWindItems >= MAX_NB_WINDOWS) return;
- for (d=1; d<10; d++) if (!cmd_key_exists('0'+d)) break;
- if (d < 10) key[3] = '0'+d; else key[2] = ' ';
- windidtodigit[id] = d;
- for (i=0; i < qWindItems; i++)
- if (windidtodigit[itemtowindid[i]] > d) break;
- for (j=qWindItems; j > i; j--) // was: qWindItems-1 -- 1997Jul26 e
- itemtowindid[j] = itemtowindid[j-1];
- itemtowindid[i] = id;
- GetWTitle( wind, title );
- InsertMenuItem( menus[windowsM], key, i+fustItem-1 );
- SetMenuItemText( menus[windowsM], i+fustItem, title );
- qWindItems++;
- }
-
- static void delWindMenuItem( short id )
- { register short i;
- for(i = 0; i < qWindItems; i++)
- { if( id == itemtowindid[i] )
- { DeleteMenuItem( menus[windowsM], i+fustItem );
- for( i++; i < qWindItems; i++ )
- itemtowindid[i-1] = itemtowindid[i];
- qWindItems--;
- break;
- }
- }
- }
-
- static void eSmudgeWindow( register short w )
- { register short i;
- if( ! wind_table[w].dirty )
- { wind_table[w].dirty = 1;
- for( i = 0; i < qWindItems; i++ )
- { if( w == itemtowindid[i] )
- { SetItemMark( menus[windowsM], i+fustItem, '◊');
- break;
- }
- }
- }
- }
-
- static void eUnSmudgeWindow( register short w, TeHANDLE hTE )
- { register short i;
- (**hTE).dirty = 0;
- if( wind_table[w].dirty )
- { wind_table[w].dirty = 0;
- for( i = 0; i < qWindItems; i++ )
- { if( w == itemtowindid[i] )
- { SetItemMark( menus[windowsM], i+fustItem, 0);
- break;
- }
- }
- }
- }
-
- static void eMaybeSmudgeWindow( short w, TeHANDLE hTE )
- {
- if( (**hTE).dirty )
- eSmudgeWindow( w );
- else
- eUnSmudgeWindow( w, hTE ); /* for Undo */
- }
-
- void select_and_show( WindowPtr wptr )
- {
- SelectWindow( wptr );
- ShowWindow( wptr );
- }
-
- /* ************* */
-
- static void wind_begin(void)
- { short i;
- long result;
- for (i=0; i<MAX_NB_WINDOWS; i++) wind_table[i].in_use = 0;
- InitGraf( &qd.thePort );
- InitFonts();
- FlushEvents( everyEvent, 0 );
- InitWindows();
- InitMenus();
- TEInit();
- eTeInit();
- InitDialogs( 0L );
- InitCursor();
-
- prefStylHilite.tsFace = bold+condense;
-
- menus[appleM] = GetMenu( appleID );
- AppendResMenu( menus[appleM], 'DRVR' );
- menus[fileM] = GetMenu( fileID );
- menus[editM] = GetMenu( editID );
- menus[findM] = GetMenu( findID );
- menus[commandM] = GetMenu( commandID );
- menus[windowsM] = GetMenu( windowsID );
-
- ClearMenuBar();
- for ( (i=appleM); (i<=windowsM); i++ ) InsertMenu(menus[i], 0);
- DrawMenuBar();
- current_menus = 0;
-
- setup_cursors();
-
- find_string = (unsigned char *)NewPtr( 256 );
- replace_string = (unsigned char *)NewPtr( 256 );
- if( find_string == NULL || replace_string == NULL )
- { SysBeep(10);
- os_quit();
- }
- find_string[0] = '\0';
- replace_string[0] = '\0';
-
- gCursorRgn = NewRgn();
- SetRectRgn(gCursorRgn, -32768, -32768, 32766, 32766);
-
- empty_buffer = NewPtr( 4 );
- *empty_buffer = 0;
-
- // gHasWNE = TrapExists(_WaitNextEvent);
- // gHasHWPriv = TrapExists(_HWPriv);
-
- gHasStdFile = (Gestalt(gestaltStandardFileAttr, &result) ? false
- : (result & (1 << gestaltStandardFile58)) != 0);
-
- readPrefs( PREFS_FILENAME );
-
- XlateRETURN = XlateRETURNp;
-
- init_ae();
- }
-
- static void wind_close( short id )
- { TeHANDLE hTE = wind_table[id].hTE;
- if (id == interaction_id)
- { HideWindow( wind_table[id].wptr );
- eTeSetSelect( hTE, 0, eTeTextLength( hTE ));
- eTeDelete( hTE );
- }
- else if (wind_table[id].in_use)
- { wind_table[id].in_use = 0;
- HideWindow( wind_table[id].wptr );
- eTeDispose( hTE );
- delWindMenuItem( id );
- DisposeControl( wind_table[id].vscroll );
- DisposeControl( wind_table[id].hscroll );
- DisposeWindow( wind_table[id].wptr );
- if (wind_table[id].buf != NULL)
- { DisposePtr( wind_table[id].buf ); wind_table[id].buf = NULL; }
- if( wind_table[id].out_buf != NULL )
- { DisposeHandle( wind_table[id].out_buf ); wind_table[id].out_buf = NULL; }
- }
- }
-
- static void wind_end(void)
- { short id;
- for (id=MAX_NB_WINDOWS-1; id>=0; id--) wind_close( id );
- eTePutScrap();
- }
-
- static pascal click_scroll();
-
- static short wind_open( unsigned char *wname, short visible, short goaway, short bold_input )
- { Rect viewRect, vScrollRect, bounds;
- short width = 80 /*(screenBits.bounds.right-SBarWidth-2*Border-11)/FontW*/;
- short height;
- short id;
-
- for (id=0; id<MAX_NB_WINDOWS; id++) if (!wind_table[id].in_use) break;
- if (id == MAX_NB_WINDOWS) return -1;
-
- height = (qd.screenBits.bounds.bottom-Border-48-SBarWidth)/FontH - id;
-
- bounds.left = 3 + id*5;
- bounds.right = bounds.left + width*FontW + SBarWidth + Border;
- bounds.top = 41 + id*(FontH+3);
- bounds.bottom = bounds.top + height*FontH + SBarWidth + Border;
-
- wind_table[id].wptr = (WindowPtr )
- NewWindow( NULL, &bounds, wname, visible, documentProc, (WindowPtr)-1L, goaway, 0L );
- if (wind_table[id].wptr == NULL) return -1;
-
- SetPort( wind_table[id].wptr );
- TextFont( prefStylNormal.tsFont );
- TextSize( prefStylNormal.tsSize );
-
- vScrollRect = (*wind_table[id].wptr).portRect;
- vScrollRect.left = vScrollRect.right-SBarWidth;
- vScrollRect.right += 1;
- vScrollRect.bottom -= SBarWidth-1;
- vScrollRect.top -= 1;
-
- wind_table[id].vscroll =
- NewControl( wind_table[id].wptr, &vScrollRect, "\p", 1, 0, 0, 0,
- scrollBarProc, 0L);
-
- if (wind_table[id].vscroll != NULL)
- { static FontInfo fInfo;
-
- vScrollRect = (*wind_table[id].wptr).portRect;
- vScrollRect.top = vScrollRect.bottom-SBarWidth;
- vScrollRect.bottom += 1;
- vScrollRect.left += (vScrollRect.right-vScrollRect.left)>>1;
- vScrollRect.right -= SBarWidth-1;
- wind_table[id].hscroll =
- NewControl( wind_table[id].wptr, &vScrollRect, "\p", 1, 0, 0, 0,
- scrollBarProc, 0L);
- if (wind_table[id].hscroll != NULL)
- {
-
- viewRect = (*wind_table[id].wptr).portRect;
- viewRect.top += Border;
- viewRect.left += Border;
- viewRect.bottom -= SBarWidth;
- viewRect.right -= SBarWidth;
-
- wind_table[id].hTE = eTeNew( wind_table[id].wptr, viewRect, prefTabs, prefWrap,
- prefAutoInd, wind_table[id].hscroll, wind_table[id].vscroll );
-
- if (wind_table[id].hTE != NULL)
- {
- eTeSetStyles( wind_table[id].hTE, &prefStylNormal, &prefStylHilite );
- wind_table[id].height = height;
- wind_table[id].bold_input = bold_input;
- wind_table[id].dirty = 0;
- wind_table[id].pos = 0;
- wind_table[id].len = 0;
- wind_table[id].buf = NULL;
- wind_table[id].out_buf = NULL;
- wind_table[id].out_len = 0;
- wind_table[id].is_file = 0;
- wind_table[id].fss.name[0]= 0;
- wind_table[id].in_use = 1;
- addWindMenuItem( id );
- return id;
- }
- DisposeControl( wind_table[id].hscroll );
- }
- DisposeControl( wind_table[id].vscroll );
- }
- DisposeWindow( wind_table[id].wptr );
- return -1;
- }
-
- static short discard_changes( short id )
- { Str255 title;
- GetWTitle( wind_table[id].wptr, title );
- ParamText( "\pDiscard changes to \"", title, "\p\"?", "\p" );
- SysBeep( 10 );
- switch (CautionAlert( ok_cancel_alertID, 0L ))
- { case 3: return 1;
- default: return 0;
- }
- }
-
- static short mem_full = 0;
- static short supress_mem_full_dialog = 0;
-
- static pascal long mem_full_err( long size )
- {
- #pragma unused (size)
- if (mem_full)
- { SetGrowZone( NULL );
- ParamText1( "\pOut of memory. The application will exit." );
- SysBeep( 10 );
- StopAlert( ok_alertID, 0L );
- ExitToShell();
- }
- mem_full = 1;
- if ( ! supress_mem_full_dialog )
- { ParamText1( "\pOut of memory." );
- SysBeep( 10 );
- StopAlert( ok_alertID, 0L );
- }
- return 0;
- }
-
- static void already_open_err( Str255 name )
- { ParamText( "\p\"", name, "\p\"", "\pis already open. Close it first." );
- SysBeep( 10 );
- StopAlert( ok_alertID, 0L );
- }
-
- static void path_too_long_err( Str255 name )
- { ParamText( "\pPath to file \"", name, "\p\" is too long.", "\p" );
- SysBeep( 10 );
- StopAlert( ok_alertID, 0L );
- }
-
- static void wind_err(void)
- { ParamText1( "\pCan't open window" );
- SysBeep( 10 );
- StopAlert( ok_alertID, 0L );
- }
-
- void io_err( short io )
- { unsigned char errnostr[16];
- switch (io)
- { case wrPermErr : ParamText1( "\pCan't write file!" ); break;
- case dupFNErr : ParamText1( "\pDuplicate file name!" ); break;
- case fBsyErr : ParamText1( "\pFile is busy!" ); break;
- case vLckdErr : ParamText1( "\pVolume is locked!" ); break;
- case fLckdErr : ParamText1( "\pFile is locked!" ); break;
- case fnfErr : ParamText1( "\pFile not found!" ); break;
- case bdNamErr : ParamText1( "\pBad filename!" ); break;
- case ioErr : ParamText1( "\pIO transfer error!" ); break;
- case dskFulErr : ParamText1( "\pDisk full!" ); break;
- case dirFulErr : ParamText1( "\pDirectory full!" ); break;
- case mFulErr : ParamText1( "\pFile is too large for memory!" ); break;
-
- case -4101 : ParamText1( "\pNo printer selected. Use the Chooser." ); break;
- default : NumToString( io, errnostr );
- ParamText( "\pIO Error! Mac error number: ", errnostr, "\p", "\p" );
- break;
- }
- SysBeep( 10 );
- StopAlert( ok_alertID, 0L );
- }
-
- static void te_limit_err(void)
- { ParamText1( "\pFile unopened due to size limit on buffer (32000 lines)." );
- SysBeep( 10 );
- StopAlert( ok_alertID, 0L );
- }
-
- static short check_TEWrite( char *ptr, long len, eTeHandle hTE, short bold )
- { eTeWrite( hTE, ptr, len, bold );
- if (mem_full) { mem_full = 0; return 1; }
- return 0;
- }
-
- short check_TEInsert( char *ptr, long len, eTeHandle hTE, short bold )
- { eTeInsert( hTE, ptr, len, bold );
- if (mem_full) { mem_full = 0; return 1; }
- return 0;
- }
-
- static short check_TECut( eTeHandle hTE )
- { eTeCut( hTE );
- if (mem_full) { mem_full = 0; return 1; }
- return 0;
- }
-
- static short check_TECopy( eTeHandle hTE )
- { eTeCopy( hTE );
- if (mem_full) { mem_full = 0; return 1; }
- return 0;
- }
-
- static short check_TEPaste( eTeHandle hTE, short bold )
- { eTePaste( hTE, bold );
- if (mem_full) { mem_full = 0; return 1; }
- return 0;
- }
-
- static short check_TEKey( char c, eTeHandle hTE, short bold, EventRecord *event )
- { eTeKey( hTE, c, (event->message & keyCodeMask) >> 8, event->modifiers, bold );
- if (mem_full) { mem_full = 0; return 1; }
- return 0;
- }
-
- short getfullpath(
- short vRefNum,
- long dirID,
- Str255 fName,
- char *Path,
- short MaxLength,
- short warn )
- {
- char *p, *q;
- long len;
- CInfoPBRec block;
- Str255 directoryName;
-
- p = &Path[MaxLength];
- *--p = '\0';
-
- len = (unsigned char)fName[0];
- p -= len;
- if (p < Path) goto too_long;
- BlockMove( &fName[1], p, len );
-
- block.dirInfo.ioNamePtr = directoryName;
- block.dirInfo.ioDrParID = dirID;
-
- do
- { block.dirInfo.ioVRefNum = vRefNum;
- block.dirInfo.ioFDirIndex = -1;
- block.dirInfo.ioDrDirID = block.dirInfo.ioDrParID;
-
- if (PBGetCatInfoSync( &block ) != noErr) return 0;
- *--p = ':';
- len = (unsigned char)directoryName[0];
- p -= len;
- if (p < Path) goto too_long;
- BlockMove( &directoryName[1], p, len );
- } while ( block.dirInfo.ioDrDirID != fsRtDirID );
-
- q = Path;
- while (*p != '\0') *q++ = *p++;
- *q = '\0';
-
- return (short )( q - Path );
-
- too_long:
- if (warn) path_too_long_err( fName );
- return 0;
- }
-
- Point SFGwhere = { 90, 82 };
- Point SFPwhere = { 106, 104 };
-
- short get_file(
- FSSpec *fss,
- short nbtypes,
- SFTypeList ftypes
- )
- {
- StandardFileReply reply;
-
- eTePutScrap();
- if (nbtypes == 0) nbtypes = -1;
- if(gHasStdFile)
- {
- StandardGetFile( 0L, nbtypes, ftypes, &reply );
- *fss = reply.sfFile;
- }
- else
- {
- SFReply reply2;
- long procID;
- SFGetFile( SFGwhere, "\p", 0L, nbtypes, ftypes, 0L, &reply2 );
- if( (reply.sfGood = reply2.good) != 0 )
- {
- GetWDInfo( reply2.vRefNum, &fss->vRefNum, &fss->parID, &procID );
- p_to_p( reply2.fName, fss->name );
- }
- }
- eTeGetScrap();
- return reply.sfGood;
- }
-
- short put_file(
- FSSpec *fss,
- Str255 prompt,
- Str255 deflt
- )
- {
- StandardFileReply reply;
-
- eTePutScrap();
- if(gHasStdFile)
- {
- StandardPutFile( prompt, deflt, &reply );
- *fss = reply.sfFile;
- }
- else
- {
- SFReply reply2;
- long procID;
- SFPutFile( SFPwhere, prompt, deflt, 0L, &reply2 );
- if( (reply.sfGood = reply2.good) != 0 )
- {
- GetWDInfo( reply2.vRefNum, &fss->vRefNum, &fss->parID, &procID );
- p_to_p( reply2.fName, fss->name );
- }
- }
- eTeGetScrap();
- return reply.sfGood;
- }
-
- static short wptr_to_id( WindowPtr w )
- { short id;
- for (id=0; id<MAX_NB_WINDOWS; id++)
- if ((wind_table[id].in_use) && (wind_table[id].wptr == (WindowPtr )w)) return id;
- return -1;
- }
-
- static void setup_view( short id )
- { WindowPtr w = wind_table[id].wptr;
- TeHANDLE hTE = wind_table[id].hTE;
- Rect view = w->portRect;
- view.top += Border;
- view.left += Border;
- view.bottom -= SBarWidth;
- view.right -= SBarWidth;
- eTeNewView( hTE, &view );
- }
-
- static void really_inval_msgrect( short w )
- { GrafPtr port = wind_table[w].wptr;
- Rect r = port->portRect;
- r.right -= (( r.right - r.left ) >> 1 ) + SBarWidth + 1;
- r.top = r.bottom - SBarWidth + 1;
- SetPort( port );
- InvalRect( &r );
- }
- static void inval_msgrect( short w )
- { if ( showPosnP ) wind_table[w].needs_inval_ticks = TickCount();
- }
-
- #if LiveScrollP
- // live scrolling -- 960716 e
- static ControlActionUPP vSBarThumbActionProcUPP;
- static ControlActionUPP hSBarThumbActionProcUPP;
- static ControlHandle globalScroller;
- static Rect globalScrollCtlRect;
- static eTeHandle globalScrollhTE;
- static short globalScrollCntlCode;
- static short globalScrollMin;
- static short globalScrollMax;
- static short globalScrollSize;
- static void vSBarThumbActionProc( void )
- {
- EventRecord event;
- short cntlVal;
- OSEventAvail(0L, &event); // a NULL event with the global mouse location
- if( event.where.h > globalScrollCtlRect.left
- && event.where.h < globalScrollCtlRect.right
- // && event.where.v > globalScrollCtlRect.top - 24
- // && event.where.v < globalScrollCtlRect.bottom + 24
- )
- { // in the scrollbar...
- cntlVal = ((event.where.v - globalScrollCtlRect.top) * globalScrollSize)
- / (globalScrollCtlRect.bottom - globalScrollCtlRect.top);
- if( cntlVal < globalScrollMin ) cntlVal = globalScrollMin;
- if( cntlVal > globalScrollMax ) cntlVal = globalScrollMax;
- if( cntlVal != globalScrollCntlCode )
- {
- SetPort( (**globalScrollhTE).macPort );
- ClipRect( &(**globalScrollhTE).macPort->portRect );
- SetControlValue( globalScroller, cntlVal );
- eTeScroll( globalScrollhTE, 0, cntlVal - globalScrollCntlCode, TRUE );
- globalScrollCntlCode = cntlVal;
- // leave the window clipped to exclude the scrollbar
- // so TrackControl's drawing is obscured
- }
- }
- }
- static void hSBarThumbActionProc( void )
- {
- EventRecord event;
- short cntlVal;
- OSEventAvail(0L, &event); // a NULL event with the global mouse location
- if( event.where.v > globalScrollCtlRect.top
- && event.where.v < globalScrollCtlRect.bottom
- // && event.where.h > globalScrollCtlRect.left - 24
- // && event.where.h < globalScrollCtlRect.right + 24
- )
- { // in the scrollbar...
- cntlVal = ((event.where.h - globalScrollCtlRect.left) * globalScrollSize)
- / (globalScrollCtlRect.right - globalScrollCtlRect.left);
- if( cntlVal < globalScrollMin ) cntlVal = globalScrollMin;
- if( cntlVal > globalScrollMax ) cntlVal = globalScrollMax;
- if( cntlVal != globalScrollCntlCode )
- {
- SetPort( (**globalScrollhTE).macPort );
- ClipRect( &(**globalScrollhTE).macPort->portRect );
- SetControlValue( globalScroller, cntlVal );
- eTeScroll( globalScrollhTE, cntlVal - globalScrollCntlCode, 0, TRUE );
- globalScrollCntlCode = cntlVal;
- // leave the window clipped to exclude the scrollbar
- // so TrackControl's drawing is obscured
- }
- }
- }
- static ControlActionUPP init_live_scroll( eTeHandle hTE, ControlHandle theControl )
- {
- globalScrollhTE = hTE;
- globalScroller = theControl;
- globalScrollCntlCode = GetControlValue( theControl );
- globalScrollCtlRect = (**theControl).contrlRect;
- LocalToGlobal( (Point *)&(globalScrollCtlRect.top) ); /* topLeft */
- LocalToGlobal( (Point *)&(globalScrollCtlRect.bottom) ); /* botRight */
- globalScrollMin = GetControlMinimum( theControl );
- globalScrollMax = GetControlMaximum( theControl );
- globalScrollSize = globalScrollMax - globalScrollMin + 1;
- if( (**theControl).contrlRect.left < (**theControl).contrlRect.top )
- { // horizontal
- globalScrollCtlRect.left += 24; // arrows
- globalScrollCtlRect.right -= 24;
- globalScrollCtlRect.top -= 2; // mouse slop
- globalScrollCtlRect.bottom += 2;
- if( hSBarThumbActionProcUPP == NULL )
- // no!: hSBarThumbActionProcUPP = NewControlActionProc(hSBarThumbActionProc);
- hSBarThumbActionProcUPP =
- (ControlActionUPP) NewRoutineDescriptor((ProcPtr)(hSBarThumbActionProc),
- kPascalStackBased, GetCurrentArchitecture());
- return hSBarThumbActionProcUPP;
- }
- else
- { // vertical
- globalScrollCtlRect.top += 24; // arrows
- globalScrollCtlRect.bottom -= 24;
- globalScrollCtlRect.left -= 2; // mouse slop
- globalScrollCtlRect.right += 2;
- if( vSBarThumbActionProcUPP == NULL )
- // no!: vSBarThumbActionProcUPP = NewControlActionProc(vSBarThumbActionProc);
- vSBarThumbActionProcUPP =
- (ControlActionUPP) NewRoutineDescriptor((ProcPtr)(vSBarThumbActionProc),
- kPascalStackBased, GetCurrentArchitecture());
- return vSBarThumbActionProcUPP;
- }
- }
- #endif // LiveScrollP
-
- static void content( short id, EventRecord *event )
- { WindowPtr w = wind_table[id].wptr;
- eTeHandle hTE = wind_table[id].hTE;
- short cntlCode;
- ControlHandle theControl;
- ChPos oldCaret;
-
- SetPort( w );
- ClipRect( &w->portRect );
- GlobalToLocal( &event->where );
- if ((cntlCode = FindControl( event->where, w, &theControl )) == 0 )
- { if (PtInRect( event->where, &(**hTE).viewRect ))
- { oldCaret = (**hTE).caretChPos;
- eTeClick( hTE, event->where, event->modifiers, event->when );
- if ( *(long *)&oldCaret != *(long *)&(**hTE).caretChPos ) inval_msgrect( id );
- }
- }
- else if (cntlCode == kControlIndicatorPart) // inThumb
- {
- #if LiveScrollP
- TrackControl( theControl, event->where, init_live_scroll( hTE, theControl ) );
- SetControlValue( theControl, globalScrollCntlCode );
- #else
- cntlCode = GetControlValue( theControl );
- TrackControl( theControl, event->where, 0L );
- if ( ( cntlCode = GetControlValue( theControl ) - cntlCode ) != 0 )
- if( (**theControl).contrlRect.left < (**theControl).contrlRect.top )
- eTeScroll( hTE, cntlCode, 0, TRUE );
- else
- eTeScroll( hTE, 0, cntlCode, TRUE );
- #endif
- }
- else
- TrackControl( theControl, event->where, (void *)-1L );
- }
-
- static void update_window( short w )
- { GrafPtr port = wind_table[w].wptr;
- Rect r = port->portRect;
- Str255 tStr;
- eTeHandle hTE;
- r.right -= (( r.right - r.left ) >> 1 ) + SBarWidth + 1;
- r.top = r.bottom - SBarWidth;
- SetPort( port );
- ClipRect( &port->portRect );
- BeginUpdate( port );
- EraseRect( &port->portRect );
- DrawControls( port );
- DrawGrowIcon( port );
- EraseRect( &r );
- MoveTo( r.left, r.top );
- LineTo( r.right, r.top );
- #ifdef USE_eTe_debug
- NumToString( eTeTextLength( wind_table[w].hTE ), tStr);
- MoveTo( r.left + 4, r.bottom - 4 );
- ClipRect( &r );
- DrawString( (ConstStr255Param )tStr );
- #else
- if ( showPosnP )
- { hTE = wind_table[w].hTE;
- MoveTo( r.left + 4, r.bottom - 4 );
- ClipRect( &r );
- NumToString( (long )(**hTE).caretChPos.v+1, tStr);
- DrawString( (ConstStr255Param )tStr );
- DrawString( "\p:" );
- NumToString( (long )(**hTE).caretChPos.h, tStr);
- DrawString( (ConstStr255Param )tStr );
- }
- #endif
- eTeUpdate( wind_table[w].hTE );
- EndUpdate( port );
- }
-
- static void grow_window( short id, Point p )
- { WindowPtr w = wind_table[id].wptr;
- long result;
- Rect r;
-
- SetPort( w );
-
- /* 16Sep92 e increase min size for H scroll bar
- SetRect(&r, 80, 80, screenBits.bounds.right, screenBits.bounds.bottom); */
- /* 13Oct92 e per: bernard@sigi.cs.colorado.edu
- SetRect(&r, 150, 80, screenBits.bounds.right, screenBits.bounds.bottom); */
- r = (**GetGrayRgn()).rgnBBox;
- r.top = 80;
- r.left = 150;
- /* 13Oct92 e */
- result = GrowWindow( w, p, &r );
- if (result == 0) return;
- SizeWindow( w, LoWord(result), HiWord(result), 1);
-
- InvalRect(&w->portRect);
- setup_view( id );
- HideControl( wind_table[id].vscroll );
- MoveControl( wind_table[id].vscroll, w->portRect.right - SBarWidth, w->portRect.top-1);
- SizeControl( wind_table[id].vscroll, SBarWidth+1, w->portRect.bottom - w->portRect.top-(SBarWidth-2));
- HideControl( wind_table[id].hscroll );
- MoveControl( wind_table[id].hscroll,
- w->portRect.right-((w->portRect.right-w->portRect.left)>>1),
- w->portRect.bottom - SBarWidth);
- SizeControl( wind_table[id].hscroll,
- ((w->portRect.right-w->portRect.left)>>1)-(SBarWidth-1),
- SBarWidth+1);
- ShowControl( wind_table[id].hscroll );
- ValidRect(&(*wind_table[id].hscroll)->contrlRect );
- ShowControl( wind_table[id].vscroll );
- ValidRect(&(*wind_table[id].vscroll)->contrlRect );
- update_window( id );
- /* dunno (sometimes appropriate, sometimes not)... eTeShowCaret( wind_table[id].hTE ); */
- }
-
- static void put_input( short id, char *ptr, long len, short cr, short flush, short freshline )
- { if (wind_table[id].in_use)
- { long len1;
- register long len2 = (wind_table[id].len - wind_table[id].pos);
- register char *buf, *p1, *p2;
- if ((len2 < 0) || flush) len2 = 0;
- len1 = ((cr)?1:0) + len2 + (long)len;
- buf = NewPtr( len1 );
- if (buf == NULL) { SysBeep(10); return; }
- p1 = buf;
- p2 = wind_table[id].buf + wind_table[id].pos;
- while (len2 > 0) { *p1++ = *p2++; len2--; }
- p2 = ptr;
- while (len > 0) { *p1++ = *p2++; len--; }
- if (cr) *p1++ = '\r';
- if (wind_table[id].buf != NULL) DisposePtr( wind_table[id].buf );
- wind_table[id].buf = buf;
- wind_table[id].pos = 0;
- wind_table[id].len = len1;
- if (freshline)
- { eTeHandle hTE = wind_table[id].hTE;
- if ( (**hTE).caretChPos.h > 0 )
- check_TEInsert( "\r", 1L, hTE, 0 );
- (**hTE).writeChPos = (**hTE).caretChPos;
- eTeShowCaret( hTE );
- }
- }
- }
-
- void put_input_str (char *text)
- {
- check_TEInsert( text, strlen(text), wind_table[interaction_id].hTE, 1 );
- put_input( interaction_id, text, strlen (text), 1, 0, 1 );
- }
-
- static void handle_interrupt()
- { interrupted = 1;
- }
-
- static short open_file( short id, short for_output, short txt, short *io )
- { short refnum;
- short file_existed = 1;
- OSErr err;
-
- if (for_output)
- {
- err = FSpCreate( &wind_table[id].fss, CREATOR, txt ? 'TEXT' : 'DATA', smSystemScript );
- file_existed = (err == dupFNErr);
- if ((err != noErr) && !file_existed)
- { *io = err; return -1; }
- }
- err = FSpOpenDF( &wind_table[id].fss, for_output ? fsRdWrPerm : fsRdPerm, &refnum );
- if (err != noErr)
- { *io = err;
- if (for_output && !file_existed)
- FSpDelete( &wind_table[id].fss );
- return -1;
- }
- *io = for_output ? SetEOF( refnum, 0L ) : noErr;
- return refnum;
- }
-
- static short close_file( short refnum, short *io )
- { *io = FSClose( refnum );
- return (*io != noErr);
- }
-
- static short read_file( short id, long line, long chr, long sesz )
- { TeHANDLE hTE = wind_table[id].hTE;
- short refnum;
- short io, io2;
- long pos = 0;
- short beep = 0;
- long size, count;
- ChPos chPos;
- Handle hData;
-
- if ( line > 32768 )
- { te_limit_err();
- return 0;
- }
- chPos.v = (line==0) ? 0 : line-1;
- chPos.h = (line==0) ? 0 : chr;
-
- SelectWindow( wind_table[id].wptr );
-
- if (wind_table[id].dirty)
- if (!discard_changes( id )) return 0;
-
- refnum = open_file( id, 0, 1, &io );
- if (refnum == -1)
- { io_err( io );
- return 0;
- }
-
- // eTeSetTextPtr( hTE, empty_buffer, 1L ); why!? 22Jul96 e
- io = GetEOF(refnum, &size);
- if( io == noErr ) {
- if( (hData = NewHandle( size + 1 )) != 0 )
- { HLock( hData );
- count = size;
- io = FSRead( refnum, &count, *hData );
- HUnlock( hData );
- if( ( io != noErr ) || ( count != size ) )
- { DisposeHandle( hData );
- if ( io == noErr ) io = ioErr;
- /* io_err( io ); will happen */
- /* added these next lines 7Jul92 e */
- mem_full = 0;
- // eTeSetTextPtr( hTE, empty_buffer, 1L ); why!? 22Jul96 e
- }
- else
- { ((char *)*hData)[size] = '\0';
- io = eTeSetTextHandleDetabify( hTE, hData, prefTabs );
- if ( io == noErr )
- { count = eTeChPosToOffset( hTE, chPos );
- eTeSetSelect( hTE, count, count + sesz );
- eTeShowCaret( hTE );
- }
- else
- { DisposeHandle( hData );
- /* io_err( io ); will happen */
- /* added these next lines 7Jul92 e */
- mem_full = 0;
- eTeSetTextPtr( hTE, empty_buffer, 1L ); // ok
- }
- }
- }
- else
- { mem_full = 0; io = mFulErr; }
- }
-
- if (close_file( refnum, &io2 ) || ((io != eofErr) && (io != noErr)))
- { if ((io != eofErr) && (io != noErr)) io_err( io ); else io_err( io2 );
- // eSmudgeWindow( id ); why!? 22Jul96 e
- return 0;
- }
- /* why!? 22Jul96 e
- if (io != noErr)
- eSmudgeWindow( id );
- else */
- eUnSmudgeWindow( id, hTE );
- return (io == noErr);
- }
-
- static void write_file( short id )
- { TeHANDLE hTE = wind_table[id].hTE;
- short refnum;
- short io, io2;
- long count;
-
- refnum = open_file( id, 1, 1, &io );
- if (refnum == -1)
- { io_err( io );
- return;
- }
-
- count = eTeTextLength( hTE );
- io = FSWrite( refnum, &count, *((**hTE).hText) );
-
- /* FlushVol added 19Apr93 e */
- if ( io == noErr )
- { io = GetVRefNum( refnum, &io2 );
- if ( io == noErr )
- io = FlushVol( 0L, io2 );
- }
-
- if (close_file( refnum, &io2 ) || (io != noErr))
- { if (io != noErr) io_err( io ); else io_err( io2 );
- return;
- }
-
- FlushVol( 0L, wind_table[id].fss.vRefNum );
-
- eUnSmudgeWindow( id, hTE );
- }
-
- short edit( FSSpec *fss, long line, long chr, long size )
- { short id;
- Str255 pname;
- int len = getfullpath( fss->vRefNum, fss->parID, fss->name, (char *)&pname[1], 254, 1 );
- pname[0] = len;
-
- if (len != 0)
- { for (id=0; id<MAX_NB_WINDOWS; id++)
- if WINDOW_OWNS_FILE_P( id, fss )
- break;
- }
- else
- id = MAX_NB_WINDOWS;
-
- if (id == MAX_NB_WINDOWS) id = wind_open( pname, FALSE, TRUE, FALSE );
- if (id < 0)
- wind_err();
- else
- { wind_table[id].fss = *fss;
- wind_table[id].is_file = 2;
- supress_mem_full_dialog = 1;
- if ( read_file( id, line, chr, size ) || wind_table[id].dirty )
- select_and_show( wind_table[id].wptr );
- else
- {
- wind_close( id );
- id = -1;
- }
- supress_mem_full_dialog = 0;
- }
- return id;
- }
-
- void save_as( short id, FSSpec *fss )
- { short i;
- Str255 ppath;
- int len = getfullpath( fss->vRefNum, fss->parID, fss->name, (char *)&ppath[1], 254, 1 );
- ppath[0] = len;
-
- for (i=0; i<MAX_NB_WINDOWS; i++)
- if WINDOW_OWNS_FILE_P( i, fss )
- { already_open_err( ppath );
- return;
- }
- wind_table[id].fss = *fss;
- if (wind_table[id].is_file != 0)
- { // don't make console into a file
- wind_table[id].is_file = 2;
- SetWTitle( wind_table[id].wptr, ppath );
- }
- if ( id != interaction_id )
- { delWindMenuItem( id );
- addWindMenuItem( id );
- }
- write_file( id );
- }
-
- static void wind_quit(void)
- { short id;
- for (id=MAX_NB_WINDOWS-1; id>=0; id--)
- { if (wind_table[id].in_use && wind_table[id].is_file && wind_table[id].dirty)
- { if (!discard_changes( id )) gDoQuit = 0;
- else wind_close( id );
- }
- }
- eTePutScrap();
- }
-
- static void handle_close( short id )
- { if (wind_table[id].is_file)
- { if ((wind_table[id].dirty) && (!discard_changes( id ))) return;
- wind_close( id );
- }
- }
-
- static char upcase( char c )
- { if( c >= 'a' && c <= 'z' ) return c - 0x20;
- else return c;
- }
-
- Boolean find_next( short id )
- { TeHANDLE hTE = wind_table[id].hTE;
- char *txt = *((**hTE).hText);
- long pos = eTeChPosToOffset( hTE, (**hTE).selActive ? (**hTE).selEnd : (**hTE).caretChPos );
- register char *start = txt + pos - 1;
- register short len = (unsigned char)find_string[0];
- register char *end = txt + eTeTextLength( hTE ) - len;
- register short i;
- Boolean again = TRUE;
- Str255 ci_string;
- if ( len == 0 ) goto not_found;
- if( find_ci )
- { for (i=len; i>0; i--)
- ci_string[i] = upcase( find_string[i] );
- /* ci_string[0] = len; -- not used */
- }
- find_begin:
- while (start < end)
- { if( find_ci )
- { for (i=len; i>0; i--)
- if( upcase( start[i] ) != (char )ci_string[i] ) goto next_pos;
- }
- else
- { for (i=len; i>0; i--)
- if (start[i] != (char )find_string[i]) goto next_pos;
- }
- eTeSetSelect( hTE, (long)(start-txt+1), (long)(start-txt+1+len) );
- return 1;
- next_pos:
- start++;
- }
- if( find_wrap && again )
- { start = txt;
- end = start + pos - len;
- again = FALSE;
- goto find_begin;
- }
- not_found:
- SysBeep(10);
- return 0;
- }
-
- void replace_next( short id )
- { TeHANDLE hTE = wind_table[id].hTE;
- if ( ! (**hTE).selActive )
- SysBeep(10);
- else
- { long len = (unsigned char)replace_string[0];
- check_TEInsert( ((char *)replace_string)+1, len, hTE, wind_table[id].bold_input );
- find_next( id );
- eTeShowCaret( hTE );
- }
- }
-
- void replace_all( short id )
- { TeHANDLE hTE = wind_table[id].hTE;
- long len = (unsigned char)replace_string[0];
-
- if ( (**hTE).selActive )
- { long pos = eTeChPosToOffset( hTE, (**hTE).selStart );
- eTeSetSelect( hTE, pos, pos );
- }
- while ( find_next( id ) )
- check_TEInsert( ((char *)replace_string)+1, len, hTE, wind_table[id].bold_input );
- eTeShowCaret( hTE );
- }
-
- static void find_dialog( short id )
- { DialogPtr dp;
- short i, s;
- Handle h;
- Rect r;
- eTePutScrap();
- ParamText( "\pFind:", "\pReplace with:", "\p", "\p" );
- dp = GetNewDialog( find_dlogID, 0L, (WindowPtr)-1L );
- if (dp == NULL) return;
- GetDialogItem( dp, 3, &i, &h, &r );
- SetDialogItemText( h, find_string );
- GetDialogItem( dp, 5, &i, &h, &r );
- SetDialogItemText( h, replace_string );
- GetDialogItem( dp, 7, &i, &h, &r);
- SetControlValue( (ControlHandle )h, find_wrap );
- GetDialogItem( dp, 8, &i, &h, &r);
- SetControlValue( (ControlHandle )h, find_ci );
- SelectDialogItemText( dp, 3, 0, find_string[0] );
- SetCursor( &qd.arrow );
- do
- { ModalDialog( 0L, &s );
- switch( s )
- { case 1:
- GetDialogItem( dp, 3, &i, &h, &r );
- GetDialogItemText( h, find_string );
- GetDialogItem( dp, 5, &i, &h, &r );
- GetDialogItemText( h, replace_string );
- GetDialogItem( dp, 7, &i, &h, &r);
- find_wrap = GetControlValue( (ControlHandle )h );
- GetDialogItem( dp, 8, &i, &h, &r);
- find_ci = GetControlValue( (ControlHandle )h );
- break;
- case 7:
- case 8:
- GetDialogItem( dp, s, &i, &h, &r );
- SetControlValue( (ControlHandle )h, GetControlValue( (ControlHandle )h ) ^ 1 );
- break;
- }
- } while( s != 1 && s != 2 );
- CloseDialog( dp );
- if( s == 1 ) find_next( id );
- eTeGetScrap();
- }
-
- static void handle_pgsetup( short id )
- {
- TeHANDLE hTE = wind_table[id].hTE;
- SetCursor(&qd.arrow);
- PageSetupDialog( hTE );
- }
-
- static void handle_print( short id )
- {
- OSErr err;
- TeHANDLE hTE = wind_table[id].hTE;
-
- SetCursor(&qd.arrow);
- err = noErr;
- if ( ! (**hTE).hPrint )
- err = PageSetupDialog( hTE );
- if( ! err )
- { err = eTePrint( hTE, true, true, wind_table[id].fss.name );
- eTePrint( nil, false, false, nil );
- }
- if( err && err != userCanceledErr && err != iPrAbort ) io_err( err );
- }
-
- static short handle_menu( long result, short id )
- { short theItem, theMenu, m, w;
- MenuHandle mh;
- Str255 name;
-
- theItem = LoWord( result );
- theMenu = HiWord( result );
- if (theMenu == 0) return 1;
- mh = GetMenuHandle( theMenu );
- for (m=appleM; m<=windowsM; m++) if (menus[m] == mh) break;
- switch (m)
- { case appleM:
- if (theItem == 1)
- { eDoDialog(0); /* about */
- }
- else if (theItem == 2)
- ;
- else
- { GetMenuItemText( menus[appleM], theItem, name );
- OpenDeskAcc( name );
- }
- break;
- case fileM:
- switch (theItem)
- { case newCommand:
- { short w = wind_open( "\pUntitled", TRUE, TRUE, FALSE );
- if (w < 0)
- wind_err();
- else
- wind_table[w].is_file = 1;
- break;
- }
- case openCommand:
- { short i;
- for (i=0; i<MAX_NB_WINDOWS; i++) if (!wind_table[i].in_use) break;
- if (i == MAX_NB_WINDOWS)
- wind_err();
- else
- { FSSpec fss;
- SFTypeList tl;
- tl[0] = 'TEXT';
- if (get_file( &fss, 1, tl ))
- edit( &fss, 0L, 0L, 0L );
- }
- break;
- }
- case closeCommand:
- if (id >= 0)
- handle_close( id );
- break;
- case saveCommand:
- if (id >= 0)
- if (wind_table[id].is_file == 2 )
- { write_file( id );
- break;
- }
- case saveasCommand:
- if (id >= 0)
- { FSSpec fss;
- if (put_file( &fss, "\pSave as:", wind_table[id].fss.name ))
- save_as( id, &fss );
- }
- break;
- case revertCommand:
- if (id >= 0)
- read_file( id, 0L, 0L, 0L );
- break;
- case pgsetupCommand:
- if (id >= 0)
- handle_pgsetup( id );
- break;
- case printCommand:
- if (id >= 0)
- handle_print( id );
- break;
- case quitCommand:
- gDoQuit = 1;
- wind_quit();
- if (gDoQuit) os_quit();
- break;
- }
- break;
- case editM:
- if (id < 0)
- SystemEdit(theItem-1);
- else
- { TeHANDLE hTE = wind_table[id].hTE;
- switch (theItem)
- { case undoCommand:
- eTeUndo( hTE );
- eMaybeSmudgeWindow( id, hTE );
- break;
- case cutCommand:
- check_TECut( hTE );
- eMaybeSmudgeWindow( id, hTE );
- break;
- case copyCommand:
- check_TECopy( hTE );
- break;
- case pasteCommand:
- check_TEPaste( hTE, wind_table[id].bold_input );
- eMaybeSmudgeWindow( id, hTE );
- break;
- case clearCommand:
- eTeDelete( hTE );
- eMaybeSmudgeWindow( id, hTE );
- break;
- case selAllCommand:
- eTeSetSelect( hTE, 0, eTeTextLength( hTE ));
- break;
- case stylesCommand:
- eStyleDlg( hTE );
- break;
- case showPosnCommand:
- showPosnP ^= 1;
- CheckItem( menus[editM], showPosnCommand, showPosnP );
- for (w=0; w<MAX_NB_WINDOWS; w++)
- if (wind_table[w].in_use) really_inval_msgrect( w );
- break;
- default: ;
- }
- eTeShowCaret( hTE );
- }
- break;
- case findM:
- if (id >= 0)
- { TeHANDLE hTE = wind_table[id].hTE;
- switch (theItem)
- { case findCommand:
- find_dialog( id );
- break;
- case againCommand:
- find_next( id );
- break;
- case replaceCommand:
- replace_next( id );
- eMaybeSmudgeWindow( id, hTE );
- break;
- case fEnterCommand:
- { long sel_sta, sel_end, sel_len = 0;
- if( (**hTE).selActive ) {
- sel_sta = eTeChPosToOffset( hTE, (**hTE).selStart );
- sel_end = eTeChPosToOffset( hTE, (**hTE).selEnd );
- sel_len = sel_end - sel_sta;
- }
- if (sel_len > 0)
- { if( sel_len > 255 ) sel_len = 255;
- buf_to_p( (unsigned short)sel_len, *((**hTE).hText) + sel_sta, find_string );
- }
- else
- SysBeep( 1 );
- break;
- }
- case replaceAllCommand:
- replace_all( id );
- eMaybeSmudgeWindow( id, hTE );
- break;
-
- #if ( CREATOR == 'Moml' )
-
- case findErrorCommand: /* thanks: 26Aug93 PSC */
- { long sel_sta, sel_end, sel_len = 0;
- if( (**hTE).selActive ) {
- sel_sta = eTeChPosToOffset( hTE, (**hTE).selStart );
- sel_end = eTeChPosToOffset( hTE, (**hTE).selEnd );
- sel_len = sel_end - sel_sta;
- sel_len = sel_len > 255 ? 255 : sel_len;
- }
- if (sel_len > 0)
- { extern void find_error(char *);
- char selection[256];
- strncpy( selection, (char *)*((**hTE).hText) + sel_sta, sel_len );
- selection[sel_len] = 0;
- find_error(selection);
- }
- else
- SysBeep( 1 );
- break;
- }
- #endif
-
- }
- eTeShowCaret( hTE );
- }
- break;
- case commandM:
- switch (theItem)
- { case interruptCommand:
- HiliteMenu(0);
- handle_interrupt();
- return 0;
- default:
- eDoCommand(theItem);
- break;
- }
- break;
- case windowsM:
- switch(theItem)
- { case 1:
- select_and_show( wind_table[interaction_id].wptr );
- break;
- case 2: /* blank line */
- break;
- default:
- theItem -= fustItem;
- if(theItem < qWindItems)
- SelectWindow( wind_table[itemtowindid[theItem]].wptr );
- break;
- }
- break;
- }
- HiliteMenu(0);
- return 1;
- }
-
- static short do_tasks()
- { short w;
- register short i;
- short men;
- EventRecord event;
- Rect r;
- RgnHandle rgn;
- long ticks = LMGetTicks();
-
- for (i=0; i<MAX_NB_WINDOWS; i++)
- if (wind_table[i].in_use)
- { if (wind_table[i].out_len > 0)
- { HLock( wind_table[i].out_buf );
- check_TEWrite( *wind_table[i].out_buf, (long)wind_table[i].out_len, wind_table[i].hTE, 0 );
- HUnlock( wind_table[i].out_buf );
- wind_table[i].out_len = 0;
- }
- /* display caret position */
- if ( wind_table[i].needs_inval_ticks != 0
- && ( wind_table[i].needs_inval_ticks + 15 ) < ticks )
- { really_inval_msgrect( i );
- wind_table[i].needs_inval_ticks = 0;
- }
- }
- w = wptr_to_id( FrontWindow() );
- if ( (!gInBackground) && (w >= 0) )
- { Cursor *curs;
- OSEventAvail(0L, &event); /* This returns a NULL event with the global mouse location */
- if( gCursRgnOK && PtInRgn( event.where, gCursorRgn ) )
- { /* punt... SetCursor( current_cursor ); */
- }
- else
- { SetPort( (GrafPtr)wind_table[w].wptr );
- r = (**wind_table[w].hTE).viewRect;
- LocalToGlobal((Point *)&(r.top)); /* topLeft */
- LocalToGlobal((Point *)&(r.bottom)); /* botRight */
- if (PtInRect( event.where, &r ))
- { curs = &ibeam_cursor;
- RectRgn(gCursorRgn, &r);
- }
- else
- { curs = &qd.arrow;
- SetRectRgn(gCursorRgn, -32768, -32768, 32766, 32766);
- rgn = NewRgn();
- RectRgn(rgn, &r);
- DiffRgn(gCursorRgn, rgn, gCursorRgn);
- DisposeRgn(rgn);
- }
- if (!gCursRgnOK || current_cursor != curs)
- { current_cursor = curs;
- SetCursor( current_cursor );
- }
- gCursRgnOK = true;
- }
- eTeIdle( wind_table[w].hTE );
- men = (wind_table[w].is_file == 2 ) ? 1 : 0;
- }
- else
- { SetRectRgn(gCursorRgn, -32768, -32768, 32766, 32766);
- gCursRgnOK = false;
- SetCursor(&qd.arrow);
- men = 2;
- }
-
- // 21Jul96 -- rainy day fund
- if ( rainy_day_fund == NULL )
- { rainy_day_fund = NewHandle(0);
- EmptyHandle( rainy_day_fund );
- }
- if ( gLowMemory )
- { supress_mem_full_dialog = 1;
- ReallocateHandle ( rainy_day_fund, kRamReserve + kRamSlop );
- if ( *rainy_day_fund != NULL )
- { SetHandleSize( rainy_day_fund, kRamReserve );
- HPurge( rainy_day_fund );
- gLowMemory = false;
- }
- else
- { men = 3;
- mem_full = 0;
- }
- supress_mem_full_dialog = 0;
- }
- else if ( *rainy_day_fund == NULL )
- { supress_mem_full_dialog = 1;
- ReallocateHandle( rainy_day_fund, kRamReserve );
- if ( *rainy_day_fund != NULL ) HPurge( rainy_day_fund );
- else
- { ParamText1( "\p We're getting low on memory; closing some windows may help." );
- SysBeep( 10 );
- CautionAlert( ok_alertID, 0L );
- gLowMemory = true;
- men = 3;
- mem_full = 0;
- }
- supress_mem_full_dialog = 0;
- }
- else ;
-
- if ( (!gInBackground) && (men != current_menus) )
- { current_menus = men;
- switch (men)
- { case 0:
- case 1:
- EnableItem( menus[fileM], newCommand );
- EnableItem( menus[fileM], openCommand );
- EnableItem( menus[fileM], saveCommand );
- EnableItem( menus[fileM], saveasCommand );
- if (men == 0)
- DisableItem( menus[fileM], revertCommand );
- else
- EnableItem( menus[fileM], revertCommand );
- EnableItem( menus[fileM], pgsetupCommand );
- EnableItem( menus[fileM], printCommand );
- EnableItem( menus[editM], selAllCommand );
- EnableItem( menus[editM], stylesCommand );
- EnableItem( menus[editM], showPosnCommand );
- EnableItem( menus[findM], 0 );
- break;
- case 2:
- EnableItem( menus[fileM], newCommand );
- EnableItem( menus[fileM], openCommand );
- DisableItem( menus[fileM], saveCommand );
- DisableItem( menus[fileM], saveasCommand );
- DisableItem( menus[fileM], revertCommand );
- DisableItem( menus[fileM], pgsetupCommand );
- DisableItem( menus[fileM], printCommand );
- DisableItem( menus[editM], selAllCommand );
- DisableItem( menus[editM], stylesCommand );
- DisableItem( menus[editM], showPosnCommand );
- DisableItem( menus[findM], 0 );
- break;
- case 3:
- DisableItem( menus[fileM], newCommand );
- DisableItem( menus[fileM], openCommand );
- EnableItem( menus[fileM], saveCommand );
- EnableItem( menus[fileM], saveasCommand );
- DisableItem( menus[fileM], revertCommand );
- DisableItem( menus[fileM], pgsetupCommand );
- DisableItem( menus[fileM], printCommand );
- DisableItem( menus[editM], selAllCommand );
- DisableItem( menus[editM], stylesCommand );
- DisableItem( menus[editM], showPosnCommand );
- DisableItem( menus[findM], 0 );
- break;
- }
- DrawMenuBar();
- }
-
- if ( (!gInBackground) && (w>=0) )
- { register EvQElPtr q = (EvQElPtr )LMGetEventQueue();
- for (q = (EvQElPtr)((QHdrPtr )q)->qHead; q != NULL; q = (EvQElPtr)q->qLink)
- if ((q->evtQWhat == keyDown) && ((char)q->evtQMessage == '.') &&
- (q->evtQModifiers & cmdKey))
- { while (GetNextEvent(keyDownMask+keyUpMask+autoKeyMask,&event) &&
- !((event.what == keyDown) && ((event.message & charCodeMask) == '.') &&
- ((event.modifiers & cmdKey) != 0) )) ;
- handle_interrupt();
- return 0;
- }
- }
- return 1;
- }
-
- /* from MacDTS */
- #define kDITop 0x0050 /* kTopLeft - for positioning the Disk */
- #define kDILeft 0x0070 /* Initialization dialogs. */
-
- void handle_activate( WindowPtr wptr, Boolean activep )
- { GrafPtr port;
- Rect r;
- short w = wptr_to_id( wptr );
- if( w >= 0 )
- { port = wind_table[w].wptr;
- r = port->portRect;
- r.left = r.right - (SBarWidth+1);
- SetPort( port );
- InvalRect( &r );
- r = port->portRect;
- r.top = r.bottom - (SBarWidth+1);
- InvalRect( &r );
- if ( activep )
- { eTeActivate( wind_table[w].hTE );
- ShowControl( wind_table[w].vscroll );
- ShowControl( wind_table[w].hscroll );
- }
- else
- { eTeDeactivate( wind_table[w].hTE );
- HideControl( wind_table[w].vscroll );
- HideControl( wind_table[w].hscroll );
- }
- }
- }
-
- static short handle_event( EventRecord *event )
- { short w;
- WindowPtr event_window;
-
- #if (CREATOR == 'Caml') || (CREATOR == 'Moml')
- extern int DoGraphEvent(EventRecord *event, WindowPtr window);
- #endif
-
- if (IsDialogEvent( event ))
- { DialogPtr dp;
- short item;
- DialogSelect( event, &dp, &item );
- return 1;
- }
-
- event_window = FrontWindow();
-
- #if (CREATOR == 'Caml') || (CREATOR == 'Moml')
- if ( DoGraphEvent( event, event_window ) ) return 1;
- #endif
-
- w = wptr_to_id( event_window );
- { switch (event->what)
- { case mouseDown:
- gCursRgnOK = false;
- switch (FindWindow(event->where,&event_window))
- { case inDesk:
- SysBeep( 10 );
- break;
- case inGoAway:
- if ((w = wptr_to_id( event_window )) >= 0)
- if (TrackGoAway(event_window,event->where)) handle_close( w );
- break;
- case inMenuBar:
- { TeHANDLE hTE = NULL;
- if( w >= 0) hTE = wind_table[w].hTE;
- eTeEditMenuUpdate( hTE, menus[editM] );
- return handle_menu( MenuSelect(event->where), w );
- }
- case inSysWindow:
- SystemClick(event,event_window);
- break;
- case inDrag:
- if ((w = wptr_to_id( event_window )) >= 0)
- DragWindow(event_window,event->where,&qd.screenBits.bounds);
- break;
- case inGrow:
- if ((w = wptr_to_id( event_window )) >= 0)
- grow_window( w, event->where );
- break;
- case inContent:
- if (event_window != FrontWindow())
- SelectWindow(event_window);
- else
- if ((w = wptr_to_id( event_window )) >= 0)
- content( w, event );
- break;
- default: ;
- }
- gLastMouseDown = *event;
- break;
- case mouseUp:
- gLastMouseUp = *event;
- break;
- case keyDown:
- case autoKey:
- { unsigned char c = event->message & charCodeMask;
- TeHANDLE hTE = (w>=0)?wind_table[w].hTE:NULL;
- if ((event->modifiers & cmdKey) != 0 && c != 3 )
- { long res;
- if (c == '=') c = '+'; else if (c == '/') c = '?';
- if (hTE != NULL) eTeEditMenuUpdate( hTE, menus[editM] );
- res = MenuKey( c );
- if( HiWord( res ) != 0 )
- return handle_menu( res, w );
- if( (hTE != NULL) && (c >= 0) && (c <= 31) )
- { check_TEKey( c, hTE, 0, event );
- inval_msgrect( w );
- }
- break;
- }
- if (hTE == NULL) break;
- #if LISPmodeP
- if( ( event->modifiers & controlKey ) != 0 )
- { eEditCommand( hTE, c, event->modifiers, wind_table[w].bold_input );
- eMaybeSmudgeWindow( w, hTE );
- inval_msgrect( w );
- }
- #endif
- else if( ( c == 127 /* del fwd */ ) || ( c <= 31 ) )
- { if( ( c == 3 /*enter*/ ) || (( c == '\r' /*cr*/ ) && ((event->modifiers & optionKey) != 0 )))
- { short id = (wind_table[w].is_file != 0) ? interaction_id : w;
- long sel_sta;
- long sel_end;
- long sel_len;
- #if EndOfInputP
- if( event->message >> 24 == 0xee) end_of_input = 1;
- #endif
- if( (**hTE).selActive ) {
- sel_sta = eTeChPosToOffset( hTE, (**hTE).selStart );
- sel_end = eTeChPosToOffset( hTE, (**hTE).selEnd );
- }
- else
- { extern void eTeGetRun( eRec **hE, long *sta, long *end );
- if ( w == interaction_id )
- { long writePos;
- eTeGetRun( hTE, &sel_sta, &sel_end );
- // try to prevent multiple input of the same text
- writePos = eTeChPosToOffset( hTE, (**hTE).writeChPos );
- if( sel_sta < writePos && writePos <= sel_end )
- sel_sta = writePos;
- }
- else
- #if LISPmodeP
- { sel_end = eTeChPosToOffset( hTE, (**hTE).caretChPos );
- sel_sta = balance_bwd( wind_table[w].hTE, 0, 1 );
- if (sel_sta < 0) sel_sta = sel_end;
- }
- #else
- sel_end = sel_sta = eTeChPosToOffset( hTE, (**hTE).caretChPos );
- #endif
- }
- eTeSetSelect( hTE, sel_end, sel_end );
- sel_len = sel_end - sel_sta;
- HLock((**hTE).hText);
- #ifndef EndOfInputP
- #define end_of_input 0
- #endif
- if (sel_len > 0)
- put_input( id, *((**hTE).hText) + sel_sta, sel_len, !end_of_input, 0, 1 );
- else
- put_input( id, NULL, 0, !end_of_input, 0, 1 ); /* not done yet!? 12Sep92 e */
- HUnlock((**hTE).hText);
- }
- else if (c == 9) /*tab*/
- { eTabCommand( hTE, event->modifiers, wind_table[w].bold_input );
- eMaybeSmudgeWindow( w, hTE );
- inval_msgrect( w );
- }
- else if ( c == '\b' /*bs*/ // don't bs over writeChPos
- && (**hTE).writeChPos.v == (**hTE).caretChPos.v
- && (**hTE).writeChPos.h == (**hTE).caretChPos.h
- )
- { SysBeep(3); // add a progressive Alert!
- }
- else
- { check_TEKey( c, hTE, wind_table[w].bold_input, event );
- if ((c == '\r') && (**hTE).autoInd)
- eTabCommand( hTE, optionKey, wind_table[w].bold_input );
- eMaybeSmudgeWindow( w, hTE );
- inval_msgrect( w );
- if ( (c=='\r' /*cr*/) || (c=='\b' /*bs*/) ) eTeShowCaret( hTE );
- }
- }
- else
- {
- #if LISPmodeP
- if (!check_TEKey( c, hTE, wind_table[w].bold_input, event ))
- if (c == ')')
- { long open_paren = balance_bwd( wind_table[w].hTE, 0, 0 );
- if (open_paren >= 0)
- { long now;
- long selstart = eTeChPosToOffset( hTE, (**hTE).caretChPos );
- eTeSetSelect( hTE, open_paren, open_paren+1 );
- eTeShowCaret( hTE );
- now = TickCount();
- while ((TickCount()-now)<10) ;
- while (!EventAvail(everyEvent,event) && ((TickCount()-now)<30)) ;
- eTeSetSelect( hTE, selstart, selstart );
- }
- }
- #else
- check_TEKey( c, hTE, wind_table[w].bold_input, event );
- #endif
- eMaybeSmudgeWindow( w, hTE );
- inval_msgrect( w );
- eTeShowCaret( hTE );
- }
- }
- break;
- case activateEvt:
- gCursRgnOK = false;
- handle_activate( (WindowPtr)event->message, ((event->modifiers & activeFlag) != 0) );
- break;
- case updateEvt:
- if ((w = wptr_to_id( (WindowPtr)event->message )) >= 0)
- { update_window(w);
- }
- else
- { GrafPtr port = (WindowPtr)event->message;
- SetPort( port );
- BeginUpdate( port );
- EndUpdate( port );
- }
- break;
- case osEvt:
- if( *(char *)(&event->message) == suspendResumeMessage )
- { gCursRgnOK = false; /* Suspend/resume is also an activate/deactivate. */
- gInBackground = !(event->message & resumeFlag);
- if( gInBackground ) eTePutScrap();
- else eTeGetScrap();
- handle_activate( FrontWindow(), !gInBackground );
- }
- /* punt mouseMovedMessage */
- break;
- case diskEvt:
- gCursRgnOK = false; /* It is not a bad idea to at least call */
- if (HiWord(event->message) != noErr) /* DIBadMount in response to a diskEvt, */
- { Point pt; /* so that the user can format a floppy. */
- SetPt( &pt, kDILeft, kDITop );
- DIBadMount( pt, event->message );
- }
- break;
- case kHighLevelEvent:
- AEProcessAppleEvent(event);
- if (gDoQuit) os_quit();
- break;
- default: ;
- }
- }
- return 1;
- }
-
- long os_get_next_event( EventRecord *event )
- { long result = 0;
- GrafPtr save;
- GetPort( &save );
- if (do_tasks())
- { beg_mf_time();
- // if (gHasWNE)
- { result = (long)( gInBackground ? gWaitTicksBG
- : (long )( (gWaitTicksFG > gMaxSleep) ? gMaxSleep
- : gWaitTicksFG) );
- result = WaitNextEvent( everyEvent, event, result, gCursorRgn );
- }
- // else
- // { SystemTask();
- // result = GetNextEvent( everyEvent, event );
- // }
- end_mf_time();
- }
- SetPort( save );
- return result;
- }
-
- long os_handle_event( EventRecord *event )
- { long result;
- GrafPtr save;
- GetPort( &save );
- result = handle_event( event );
- SetPort( save );
- return result;
- }
-
- void os_event_check( void )
- { EventRecord event;
- os_get_next_event( &event );
- os_handle_event( &event );
- #if USE_EVENTCHK_TIMER
- next_eventchk_ticks = 0;
- #else
- next_eventchk_ticks = LMGetTicks() + TicksBetweenEventChecks;
- #endif
- if ( interrupted ) { interrupted = 0; raise(SIGINT); }
- }
-
- void os_quit()
- {
- #if ANSIquitP
- exit(0);
- #else
- wind_end();
- #if USE_EVENTCHK_TIMER
- cancel_eck_timer();
- #endif
- ExitToShell();
- #endif
- }
-
- /* ******* console io ******* */
-
- static GrowZoneUPP mem_full_errUPP;
-
- static short main_internal( )
- { short i;
- MaxApplZone();
- for (i = 0; i < 10; i++)
- MoreMasters();
- /* CouldAlert( ok_alertID ); */
- mem_full_errUPP = NewGrowZoneProc(mem_full_err);
- SetGrowZone( mem_full_errUPP );
-
- wind_begin();
-
- #if ANSIquitP
- atexit(wind_quit);
- #endif
-
- SetCursor( current_cursor );
-
- ParamText1( "\p" );
-
- #if USE_EVENTCHK_TIMER
- init_eck_timer();
- #endif
-
- return 0;
- }
-
- static short console_initialized = 0;
-
- WindowPeek os_console_new( unsigned char *name )
- { short id;
- WindowPeek wp;
- if( !console_initialized )
- { main_internal();
- console_initialized = 1;
- }
- id = wind_open( name, FALSE, FALSE, TRUE );
- if( id < 0 ) return (WindowPeek )0;
- interaction_id = id;
- delWindMenuItem( interaction_id );
- wp = (WindowPeek )wind_table[id].wptr;
- wp->refCon = (long )id;
- return(wp);
- }
-
- long os_console_chars_ready(WindowPeek wp)
- { short id = wp->refCon;
- return wind_table[id].len - wind_table[id].pos;
- }
-
- long os_console_read( WindowPeek wp, unsigned char *ptr, long cnt )
- {
- #if ReadHangsP
- long result;
- do
- { result = os_console_read_nohang( wp, ptr, cnt );
- } while (result == 0);
- return result;
- #else
- return os_console_read_nohang( wp, ptr, cnt );
- #endif
- }
-
- long os_console_read_nohang( WindowPeek wp, unsigned char *ptr, long cnt )
- { long result = 0;
- GrafPtr save;
- GetPort( &save );
- if( cnt > 0 )
- { register unsigned char *p1 = ptr;
- short id = wp->refCon;
- EventRecord event;
- do
- { os_get_next_event( &event );
- os_handle_event( &event );
- if( interrupted )
- goto ocr_done;
- else
- { register unsigned char *p2 = (unsigned char *)wind_table[id].buf + wind_table[id].pos;
- register long len = wind_table[id].len - wind_table[id].pos;
- register short i = 0;
- if (len > cnt) len = cnt;
- cnt = len; /* nohang */
- while ( i < len )
- { register unsigned char c = p2[i++];
- if (c == '\r')
- {
- if (XlateRETURN != 0) c = '\n';
- len = i; /* to exit inner loop */
- cnt = i; /* to exit outer loop */
- }
- *p1++ = c;
- }
- wind_table[id].pos += i;
- cnt -= i;
- result += i;
- }
- #if EndOfInputP
- if( end_of_input )
- {
- // end_of_input = 0;
- goto ocr_done;
- }
- #endif
- } while( cnt > 0 );
- }
- ocr_done:
- SetPort( save );
- return result;
- }
-
- long os_console_write( WindowPeek wp, unsigned char *ptr, long cnt)
- { long result = 0;
- GrafPtr save;
- short id = (short )wp->refCon;
-
- GetPort( &save );
-
- if (!(wp->visible))
- select_and_show( (WindowPtr )wp );
-
- if (XlateRETURN)
- {
- register unsigned char *p1 = ptr, *p2 = ptr+cnt;
- register short len = wind_table[id].out_len;
- register unsigned char *p3;
- if( wind_table[id].out_buf == NULL )
- { wind_table[id].out_buf = NewHandle( OUT_BUF_LEN );
- if( wind_table[id].out_buf == NULL )
- { SysBeep(10);
- return result;
- }
- }
- HLock( wind_table[id].out_buf );
- p3 = (unsigned char *)*wind_table[id].out_buf;
-
- while( p1 < p2 )
- { register unsigned char c = *p1++;
- if (c == '\n') { p3[len++] = '\r'; goto output; }
- p3[len++] = c;
- if (len == OUT_BUF_LEN)
- { output:
- if( check_TEWrite( (char *)p3, (long)len, wind_table[id].hTE, 0 ) ) goto werror;
- wind_table[id].out_len = 0;
- len = 0;
- }
- }
- wind_table[id].out_len = len;
- result = cnt;
- werror:
- SetPort( save );
- HUnlock( wind_table[id].out_buf );
- }
- else
- {
- if( check_TEWrite( (char *)ptr, (long)cnt, wind_table[id].hTE, 0 ) == 0 )
- result = cnt;
- }
- return result;
- }
-
- long os_console_close( WindowPeek wp )
- { long result = 0;
- GrafPtr save;
- short id = (short )wp->refCon;
- GetPort( &save );
- if( id < 0 )
- result = -1;
- else
- wind_close( id );
- SetPort( save );
- return result;
- }
-
- /*--------------------------------------------------------------------------*/
-
- /* Used to check for any unread required parameters. Returns true if we
- ** missed at least one. */
-
- static Boolean MissedAnyParameters(AppleEvent *message)
- {
- OSErr err;
- DescType ignoredActualType;
- AEKeyword missedKeyword;
- Size ignoredActualSize;
- EventRecord event;
-
- err = AEGetAttributePtr( /* SEE IF PARAMETERS ARE ALL USED UP. */
- message, /* AppleEvent to check. */
- keyMissedKeywordAttr, /* Look for unread parameters. */
- typeWildCard, /* So we can see what type we missed, if any. */
- &ignoredActualType, /* What it would have been if not coerced. */
- (Ptr)&missedKeyword, /* Data area. (Keyword not handled.) */
- sizeof(missedKeyword), /* Size of data area. */
- &ignoredActualSize /* Actual data size. */
- );
-
- /* No error means that we found some unused parameters. */
-
- if (err == noErr) {
- event.message = *(long *) &ignoredActualType;
- event.where = *(Point *) &missedKeyword;
- err = errAEEventNotHandled;
- }
-
- /* errAEDescNotFound means that there are no more parameters. If we get
- ** an error code other than that, flag it. */
-
- return(err != errAEDescNotFound);
- }
-
- #if ( CREATOR == 'Moml' )
-
- static void get_app_name( void )
- {
- //unsigned char *CurApName = LMGetCurApName();
- ProcessInfoRec pir;
- ProcessSerialNumber psn;
- char path[512];
- short w;
-
- psn.highLongOfPSN = 0;
- psn.lowLongOfPSN = kCurrentProcess;
- pir.processInfoLength = sizeof(pir);
- pir.processName = 0;
- pir.processAppSpec = &appFSS;
- GetProcessInformation( &psn, &pir );
- w = getfullpath( appFSS.vRefNum, appFSS.parID, appFSS.name, path, 511, 1 );
- e_setenv( "PATH_TRANSLATED", path, 0 );
- if( image_name == NULL && strcmp( ".app", &path[w-4] ) == 0 && w < 510 )
- { // make image name from app name: foo.app => foo.image
- strcpy( &path[w-3], "image" );
- image_name = malloc( w + 3 );
- if( image_name ) strncpy( image_name, path, w + 3 );
- }
- gMadeAppFSS = true;
- }
-
- #else
- static void get_app_name( void )
- {
- }
- #endif
-
- static OSErr OpenDocEventHandler(AppleEvent *message, AppleEvent *reply, short mode)
- {
- #pragma unused( reply )
- OSErr err;
- OSErr err2;
- AEDesc theDesc;
- FSSpec theFSS;
- short loop;
- long numFilesToOpen;
- AEKeyword ignoredKeyWord;
- DescType ignoredType;
- Size ignoredSize;
- char path[512];
- short w;
- FInfo theFInfo;
-
- if( ! gMadeAppFSS ) get_app_name( );
-
- theDesc.dataHandle = nil;
- /* Make sure disposing of the descriptors is okay in all cases.
- ** This will not be necessary after 7.0b3, since the calls that
- ** attempt to create the descriptors will nil automatically
- ** upon failure. */
-
- if ( (err = AEGetParamDesc( message, keyDirectObject, typeAEList, &theDesc )) != 0 )
- return(err);
-
- if ( ! MissedAnyParameters( message ) ) {
-
- /* Got all the parameters we need. Now, go through the direct object,
- ** see what type it is, and parse it up. */
-
- err = AECountItems(&theDesc, &numFilesToOpen);
- if (!err)
- { /* We have numFilesToOpen that need opening, as either a window
- ** or to be printed. Go to it... */
-
- for (loop = 1; ((loop <= numFilesToOpen) && (!err)); ++loop)
- { err = AEGetNthPtr( /* GET NEXT IN THE LIST... */
- &theDesc, /* List of file names. */
- loop, /* Item # in the list. */
- typeFSS, /* Item is of type FSSpec. */
- &ignoredKeyWord, /* Returned keyword -- we know. */
- &ignoredType, /* Returned type -- we know. */
- (Ptr)&theFSS, /* Where to put the FSSpec info. */
- sizeof(theFSS), /* Size of the FSSpec info. */
- &ignoredSize /* Actual size -- we know. */
- );
- if (err) break;
-
- FSpGetFInfo( &theFSS, &theFInfo );
- if ( theFInfo.fdType != 'TEXT' )
- {
- #ifdef PFILmode
- if( theFInfo.fdType == 'FILi' ) pfil_ae_load( &theFSS );
- else
- #endif
- #if ( CREATOR == 'Moml' )
- w = getfullpath( theFSS.vRefNum, theFSS.parID, theFSS.name, path, 511, 1 );
- if( !been_there_done_that && theFInfo.fdType == 'BINA' && theFInfo.fdCreator == 'Moml' )
- {
- been_there_done_that = true;
- image_name = malloc( w + 1 );
- if( image_name ) strncpy( image_name, path, w + 1 );
- }
- else
- #elif ( CREATOR == 's48e' )
- char *cmnd = "vm -i ";
- w = getfullpath( theFSS.vRefNum, theFSS.parID, theFSS.name, path, 511, 1 );
- if ( ( theFInfo.fdType == 'BINA' ) && w )
- {
- check_TEInsert( cmnd, 6, wind_table[interaction_id].hTE, 1 );
- check_TEInsert( path, w, wind_table[interaction_id].hTE, 1 );
- put_input( interaction_id, cmnd, 6, 0, 0, 1 );
- put_input( interaction_id, path, w, 1, 0, 0 );
- }
- else
- #else
- #pragma unused( path )
- #endif
- SysBeep( 3 );
- continue;
- }
- gPrintPage = mode;
- /* Open the window off-screen if we are printing.
- ** We use the gPrintPage global to flag this. Normally, the
- ** gPrintPage global is to tell ImageDocument if we are imaging
- ** to the window or to paper. We don't need it for this yet,
- ** as we can't image the document until it is opened. DoNewWindow()
- ** uses gPrintPage as a flag to open the window off-screen, but
- ** visible, so that PrintMonitor can use the title of the window
- ** as the document name that is being printed. */
-
- if ( 1 ) /* was ( w ); moved getfullpath inside bin case 18Jul96 e */
- {
- w = edit( &theFSS, 0L, 0L, 0L );
-
- if ( gPrintPage && w >= 0 )
- {
- err = eTePrint( wind_table[w].hTE, (mode == 2), (loop == 1),
- wind_table[w].fss.name );
- mode = 1; /* No interaction mode (mode == 2) only valid
- ** for the first printed document. */
- wind_close( w );
- }
- }
- else err = errAEEventNotHandled; /* file pathname too long */
- }
- if (gPrintPage)
- { eTePrint( nil, false, false, nil ); /* cleanup */
- gPrintPage = 0; /* back to normal */
- }
- }
- }
- err2 = AEDisposeDesc(&theDesc);
- return(err ? err : err2);
- }
-
- static Boolean install_aehandler( AEEventClass cl, AEEventID id, ProcPtr p )
- { OSErr err;
- AEEventHandlerUPP upp = NewAEEventHandlerProc(p);
-
- if ( upp == NULL ) err = memFullErr;
- else err = AEInstallEventHandler( cl, id, upp, 0L, false );
- if (err)
- { io_err(err);
- return false;
- }
- return true;
- }
-
- static pascal OSErr DoAEOpenApplication( AppleEvent *message, AppleEvent *reply, long refcon )
- {
- #pragma unused( message, reply, refcon )
- get_app_name( );
- return(noErr);
- }
-
- static pascal OSErr DoAEOpenDocuments( AppleEvent *message, AppleEvent *reply, long refcon )
- {
- #pragma unused( refcon )
- gCursRgnOK = false;
- return( OpenDocEventHandler( message, reply, 0 ) ); /* 0 means regular open document */
- }
-
- #define kTimeOutInTicks (60 * 30) /* 30 second timeout. */
-
- static pascal OSErr DoAEPrintDocuments(AppleEvent *message, AppleEvent *reply, long refcon)
- {
- #pragma unused( refcon )
- short openMode;
- ProcessSerialNumber cpsn, fpsn;
- Boolean procsSame;
-
- gCursRgnOK = false;
- openMode = 1;
- if (!AEInteractWithUser(kTimeOutInTicks, nil, nil))
- ++openMode;
-
- GetCurrentProcess(&cpsn); /* We may have been moved to the front. */
- GetFrontProcess(&fpsn);
- SameProcess(&cpsn, &fpsn, &procsSame);
- gInBackground = !procsSame;
-
- return( OpenDocEventHandler( message, reply, openMode ) );
- /* openMode is either 1 or 2, depending if user interaction is okay. */
- }
-
- static pascal OSErr DoAEQuitApplication( AppleEvent *message, AppleEvent *reply, long refcon )
- {
- #pragma unused( message, reply, refcon )
- gCursRgnOK = false;
- gDoQuit = 1;
- wind_quit();
- return( gDoQuit ? noErr : errAEEventNotHandled );
- }
-
- static OSErr DoScriptAsFile( FSSpec *theFSS )
- {
- OSErr err = noErr;
- short len;
- char path[512];
-
- if( (len = getfullpath( theFSS->vRefNum, theFSS->parID, theFSS->name, path, 511, 1 )) != 0 )
- {
- put_input( interaction_id, dosc_open_str, dosc_open_str_sz, 0, 0, 1 );
- put_input( interaction_id, path, len, 0, 0, 0 );
- put_input( interaction_id, dosc_clos_str, dosc_clos_str_sz, 1, 0, 0 );
- }
- else err = errAEEventNotHandled;
- return err;
- }
-
- #ifdef DoSCRIPT
- AppleEvent gAEEvent;
- AppleEvent gAEReply;
- int gAESuspn;
- #endif
-
- static pascal OSErr DoAEDoScript( AppleEvent *theAEEvent, AppleEvent *theAEReply, long *theRefCon)
- {
- #pragma unused( theRefCon )
- OSErr theErr;
- DescType typeCode;
- Size sizeOfParam, actualSize;
- char ourScriptText[256];
- FSSpec ourScriptFSpec;
-
- /* Get the script to run */
-
- theErr = AESizeOfParam( theAEEvent, keyDirectObject, &typeCode, &sizeOfParam);
- if (theErr != noErr)
- { /*
- If we fail here just return the error. We don't need to do any clean up since
- we've allocated nothing on the heap yet. The Apple Event Manager automatically
- adds the error number to the reply as keyErrorNumber for non zero handler returns.
- */
- return theErr;
- }
- else if ((typeCode == typeChar) || (typeCode == typeStyledText) || (typeCode == typeIntlText))
- {
- theErr = AEGetParamPtr( theAEEvent, keyDirectObject, typeChar, &typeCode,
- (Ptr)ourScriptText, sizeof(ourScriptText), &actualSize);
- if (theErr == noErr)
- if ( MissedAnyParameters( theAEEvent ) )
- theErr = errAEEventNotHandled;
- else
- { check_TEInsert( ourScriptText, actualSize, wind_table[interaction_id].hTE, 1 );
- put_input( interaction_id, ourScriptText, actualSize, 1, 0, 1 );
- }
- }
- else if (typeCode == typeAlias)
- {
- theErr = AEGetParamPtr( theAEEvent, keyDirectObject, typeFSS, &typeCode,
- (Ptr)&ourScriptFSpec, sizeof(ourScriptFSpec), &actualSize);
- if ( theErr == noErr )
- if ( MissedAnyParameters( theAEEvent ) )
- theErr = errAEEventNotHandled;
- else theErr = DoScriptAsFile( &ourScriptFSpec );
- }
- else theErr = errAEEventNotHandled;
- #ifdef DoSCRIPT
- if ( theErr == noErr )
- {
- gAEEvent = *theAEEvent;
- gAEReply = *theAEReply;
- gAESuspn = 1;
- gReceivedAE = -1;
- return AESuspendTheCurrentEvent( theAEEvent );
- }
- #else
- #pragma unused( theAEEvent, theAEReply, theRefCon )
- #endif
- return theErr;
- }
-
- #ifdef DoSCRIPT
- static pascal OSErr DoAEwww2( AppleEvent *theAEEvent, AppleEvent *theAEReply, long *theRefCon)
- {
- #pragma unused( theAEEvent, theRefCon )
- OSErr theErr = noErr;
- //char ourScriptText[256];
-
- if( gAESuspn )
- {
- TeHANDLE hTE = wind_table[interaction_id].hTE;
- char *txt;
- int len = eTeTextLength( hTE );
- HLock( (**hTE).hText );
- txt = *((**hTE).hText);
- theErr = AEPutParamPtr( theAEReply, keyDirectObject, typeChar, (Ptr)txt, len);
- // sprintf( ourScriptText+1, "www2: %d", err );
- // ourScriptText[0] = strlen(ourScriptText+1);
- // DebugStr( (unsigned char *)ourScriptText );
- HUnlock( (**hTE).hText );
- gAESuspn = 0;
- }
- return theErr;
- }
- #endif
-
- #if 0
- static pascal OSErr DoAEwww( AppleEvent *theAEEvent, AppleEvent *theAEReply, long *theRefCon)
- {
- OSErr theErr;
- DescType typeCode;
- Size sizeOfParam, actualSize;
- char ourScriptText[256];
- FSSpec ourScriptFSpec;
-
- theErr = AEGetParamPtr( theAEEvent, keyDirectObject, typeChar, &typeCode,
- (Ptr)ourScriptText, sizeof(ourScriptText), &actualSize);
- if (theErr == noErr)
- { check_TEInsert( ourScriptText, actualSize, wind_table[interaction_id].hTE, 1 );
- put_input( interaction_id, ourScriptText, actualSize, 1, 0, 1 );
- }
- gAEEvent = *theAEEvent;
- gAEReply = *theAEReply;
- gAESuspn = 1;
- return AESuspendTheCurrentEvent( theAEEvent );
- }
- #endif
-
- #ifdef DoSCRIPT
- OSErr finish_AEDoScript( void )
- {
- if( gAESuspn )
- {
- int i;
- // char ourScriptText[256];
- AEEventHandlerUPP upp = NewAEEventHandlerProc(DoAEwww2);
- OSErr err = AEResumeTheCurrentEvent( &gAEEvent, &gAEReply, upp, 0 );
- // sprintf( ourScriptText+1, "www1: %d %x %x %x", err, gAEEvent, gAEReply, upp );
- // ourScriptText[0] = strlen(ourScriptText+1);
- // DebugStr( (unsigned char *)ourScriptText );
- if( gAESuspn && err == noErr )
- for( i = 0; gAESuspn && i < 10; i++ ) os_event_check();
- return err;
- }
- return errAEEventNotHandled;
- }
- #endif
-
-
- #ifdef PFILmode
-
- extern int pfil_ae_eval( char *in_buf, int in_siz, char* ou_buf, int ou_siz );
-
- static pascal OSErr DoAEDoEval( AppleEvent *theAEEvent, AppleEvent *theAEReply, long *theRefCon)
- {
- OSErr theErr;
- DescType typeCode;
- Size sizeOfParam, actualSize;
- char inScriptText[256];
- char ouScriptText[256];
- FSSpec ourScriptFSpec;
-
- /* Get the script to run */
-
- theErr = AESizeOfParam( theAEEvent, keyDirectObject, &typeCode, &sizeOfParam);
- if (theErr != noErr)
- { return theErr;
- }
- else if ((typeCode == typeChar) || (typeCode == typeStyledText) || (typeCode == typeIntlText))
- {
- theErr = AEGetParamPtr( theAEEvent, keyDirectObject, typeChar, &typeCode,
- (Ptr)inScriptText, sizeof(inScriptText), &actualSize);
- if (theErr == noErr)
- if ( MissedAnyParameters( theAEEvent ) )
- theErr = errAEEventNotHandled;
- }
- else if (typeCode == typeAlias)
- {
- theErr = AEGetParamPtr( theAEEvent, keyDirectObject, typeFSS, &typeCode,
- (Ptr)&ourScriptFSpec, sizeof(ourScriptFSpec), &actualSize);
- if ( theErr == noErr )
- if ( MissedAnyParameters( theAEEvent ) )
- theErr = errAEEventNotHandled;
- else theErr = errAEEventNotHandled; /* DoScriptAsFile( &ourScriptFSpec ); */
- }
- else theErr = errAEEventNotHandled;
-
- if ( theErr == noErr )
- {
- actualSize = pfil_ae_eval( inScriptText, actualSize,
- ouScriptText, sizeof(ouScriptText) );
- theErr = AEPutParamPtr( theAEReply, keyDirectObject, typeChar,
- (Ptr)ouScriptText, actualSize);
- }
- return theErr;
- }
-
- #endif
-
- static void init_ae()
- {
- long result;
-
- gHasAppleEvents = (Gestalt(gestaltAppleEventsAttr, &result) ? false : result != 0);
-
- if (gHasAppleEvents)
- install_aehandler( kCoreEventClass, kAEOpenApplication, (ProcPtr )DoAEOpenApplication )
- && install_aehandler( kCoreEventClass, kAEOpenDocuments, (ProcPtr )DoAEOpenDocuments )
- && install_aehandler( kCoreEventClass, kAEPrintDocuments, (ProcPtr )DoAEPrintDocuments )
- && install_aehandler( kCoreEventClass, kAEQuitApplication, (ProcPtr )DoAEQuitApplication )
- && install_aehandler( kAEMiscStandards, kAEDoScript, (ProcPtr )DoAEDoScript )
- // && install_aehandler( 'WWWΩ', 'sdoc', (ProcPtr )DoAEwww )
- #ifdef PFILmode
- && install_aehandler( kAEMiscStandards, (OSType )'eval', (ProcPtr )DoAEDoEval )
- #endif
- ;
- }
-
- /*--------------------------------------------------------------------------*/
-
-